<?php
/**
 * 访问日志
 * @since 1.0 - 2011-11-12
 * @author huanran.zhao
 */

class VisitModel {
	
	/**
	 * 设置访问日志
	 */
	public function setVisitLog($name = ''){
		//是否开启访问日志记录
		if(!C('access_log')) return false;
		//防止数据重复(同一个control/action只能存在一条数据)
		$lastData = DB('visit_log')->field("`control`,`action`")->where("user_name='{$_SESSION['username']}'")->order("time DESC")->find();
		if($lastData['control']==CONTROLLER_NAME AND $lastData['action']==ACTION_NAME) return false;
		// id/user_name用户名/user_id用户id/title标题/menu_id菜单id/control控制/action方法/ip/time访问时间/description描述
		$title = $name?$name:$this->getTitle();		//标题
		if(empty($title)) return false;	//找不到菜单名称直接返回不记录
		$method = $this->getMethod();	//请求方式和url参数:

		$data['title']		= !empty($name)?$name:$title['title'];
		$data['menu_id']	= $title['id']?$title['id']:0;
		$data['ip']			= get_client_ip();	//ip
		$data['control']	= CONTROLLER_NAME;	//控制器
		$data['action']		= ACTION_NAME;		//方法
		$data['user_id']	= My::user('id');
		$data['user_name']	= My::user('username');
		$data['time']		= time();
		$data['method']		= $method['method'];	
		$data['query']		= $method['query'];		
		//$data['description']= urlencode(DB('')->getLastSQL());
		DB('visit_log')->add($data);
		return true;
	}
	
	/**
	 * 
	 * 得到当前访问菜单的名称
	 */
	private function getTitle(){
		$result = false;
		//得到session菜单列表数组
		$modules = M('menu')->getMenu(true);
		//当前url
		$url = CONTROLLER_NAME.'/'.ACTION_NAME;
		//得到当前菜单名称
		if(is_array($modules))
		foreach($modules as $key=>$value){
			$url = strtolower($url);
			$module_url = str_replace('index.php?','',isset($value['link'])?strtolower($value['link']):'');
			$module_url = str_replace('&amp;','&',$module_url);
			parse_str($module_url,$module_array);//分析url
			$module_array['act'] = !empty($module_array['act'])?$module_array['act']:'index';//action为空时,默认index
			$module_url=My::arr2var($module_array,'app').'/'.My::arr2var($module_array,'act');
			//echo "<pre>";print_r($value);
			if(($url == $module_url)){
				$result=$value;
				break;
			}
		}
		return $result;
	}
	
	/**
	 * 
	 * 获得请求方式和传递的参数
	 */
	private function getMethod() {
		$method['method'] = '未知';
		$str = '';

		$method['method'] = $_SERVER['REQUEST_METHOD'];
		unset($_GET['app']);
		unset($_GET['act']);
		$_GET = array_filter($_GET);
		if(isset($_GET['_'])) unset($_GET['_']);
		$method['query'] = http_build_query($_GET);

		return $method;
	} 
   
}